package com.bnz.service.impl;

import com.bnz.controller.DTO.UserDto;
import com.bnz.dao.UserDao;
import com.bnz.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author xy
 * @date 2022/10/27
 */
@Service
public class SysDetailService implements UserDetailsService {
    @Autowired
    UserDao userDao;


    //注册
    public void register(User user){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password =user.getPassword();
        password = encoder.encode(password);
        user.setPassword(password);
        userDao.save(user);
    }
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userDao.findByUsernameIs(s);


        return buildUserDto(user);
    }
    private UserDto buildUserDto(User user){
        UserDto userDto = new UserDto();
        userDto.setUserename(user.getUsername());
        userDto.setPassword(user.getPassword());
        List<String> roleList = new ArrayList<>();
        user.getRoles().forEach(role->{
            role.getPermissions().forEach(pers ->{
                System.out.println("ROLE_"+pers.getPersFlage());
                roleList.add("ROLE_"+pers.getPersFlage());
            });
        });
        userDto.setRoleList(roleList);
        return userDto;
    }
}
